package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class DocumentServlet
 */
@WebServlet(urlPatterns = { "/Document", "/document", "/DocumentServlet", "/documentServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class DocumentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public DocumentServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("new")) {

			if (RightUtil.<DocumentModel> checkInsertRight()) {

				// TODO : MORE CODE HERE

				response.sendRedirect("documentNew.jsp");
			} else {
				// TODO no right
			}
		} else if (mode.equalsIgnoreCase("edit")) {

			DocumentModel query = new DocumentModel();
			String id = request.getParameter("id");
		
			query.setId(Integer.parseInt(id));

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());

			DocumentModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {

				// TODO : MORE CODE HERE

				request.setAttribute("document", obj);
				getServletContext().getRequestDispatcher("/documentEdit.jsp").forward(request, response);

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("view")) {

			DocumentModel query = new DocumentModel();
			String id = request.getParameter("id");
			query.setId(Integer.parseInt(id));

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());

			DocumentModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				// TODO : LOAD MASTER DATA HERE
				// It's specific code that cannot be generated

				request.setAttribute("document", obj);
				response.sendRedirect("documentView.jsp");

			} else {
				// TODO : data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			DocumentModel obj = new DocumentModel();

			// SET NAME here

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());
			int res = 0;

			try {
				String strName = request.getParameter("document_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setDocumentName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("document", "" + res);
					out.println(resultXML);
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		} else if (mode.equalsIgnoreCase("delete")) {

			DocumentModel query = new DocumentModel();
			String id = request.getParameter("id");
			String objectType=request.getParameter("objectType");
			String objectId=request.getParameter("objectId");
			query.setId(Integer.parseInt(id));

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());

			int res = Integer.MIN_VALUE;
			try {
				res = dal.delete(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (res == 0) {
				// TODO success
				response.sendRedirect("documentList.jsp?objectType="+objectType+"&objectId="+objectId);
			} else {
				// TODO fail
				PrintWriter out = response.getWriter();
				out.println("Cannot delete!");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		String mode = request.getParameter("mode");
		

		if (mode.equalsIgnoreCase("insert")) {

			DocumentModel obj = new DocumentModel();
//			String code = request.getParameter("code");
//					obj.setCode(code);
//
//String is_template = request.getParameter("is_template");
//					obj.setIsTemplate(is_template.equalsIgnoreCase("true")
//							|| is_template.equalsIgnoreCase("1"));

String object_type = request.getParameter("objectType");
					obj.setObjectType(object_type);

String object_id = request.getParameter("objectId");
                    if (object_id != null && !object_id.isEmpty()) {
					    obj.setObjectId(Integer.parseInt(object_id));
                    }

//String status = request.getParameter("status");
//                    if (status != null && !status.isEmpty()) {
//					    obj.setStatus(Integer.parseInt(status));
//                    }
//
//String notification = request.getParameter("notification");
//                    if (notification != null && !notification.isEmpty()) {
//					    obj.setNotification(Integer.parseInt(notification));
//                    }



String document_name = request.getParameter("document_name");
					obj.setDocumentName(document_name);

//String extension = request.getParameter("extension");
//					obj.setExtension(extension);

String description = request.getParameter("description");
					obj.setDescription(description);

String remark = request.getParameter("remark");
					obj.setRemark(remark);

String document_type = request.getParameter("document_type");
                    if (document_type != null && !document_type.isEmpty()) {
					    obj.setDocumentType(Integer.parseInt(document_type));
                    }

			obj.setCreator(SessionUtil.getCurrentUserID());

			if (CommonBll.checkInputs(obj)) {
				GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());

				int res = 0;
				try {
					res = dal.insert(obj);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (res > 0) {
					// TODO : success, refresh cache and redirect to somewhere
					response.sendRedirect("documentList.jsp?objectType="+object_type+"&objectId="+object_id);
				} else {
					// TODO : processing error here
				}
			} else {

				// invalid input

				request.setAttribute("document", obj);
				getServletContext().getRequestDispatcher("/documentInput.jsp").forward(request, response);

			}
		} else if (mode.equalsIgnoreCase("update")) {

			DocumentModel query = new DocumentModel();
			String id = request.getParameter("id");
			
			query.setId(Integer.parseInt(id));

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());

			DocumentModel obj = null;
			try {
				obj = dal.select(query);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (obj != null) {
				
//				String code = request.getParameter("code");
//				obj.setCode(code);
//
//String is_template = request.getParameter("is_template");
//				obj.setIsTemplate(is_template.equalsIgnoreCase("true")
//						|| is_template.equalsIgnoreCase("1"));

String object_type = request.getParameter("objectType");
				obj.setObjectType(object_type);

String object_id = request.getParameter("objectId");
                if (object_id != null && !object_id.isEmpty()) {
				    obj.setObjectId(Integer.parseInt(object_id));
                }

//String status = request.getParameter("status");
//                if (status != null && !status.isEmpty()) {
//				    obj.setStatus(Integer.parseInt(status));
//                }
//
//String notification = request.getParameter("notification");
//                if (notification != null && !notification.isEmpty()) {
//				    obj.setNotification(Integer.parseInt(notification));
//                }



String document_name = request.getParameter("document_name");
				obj.setDocumentName(document_name);

//String extension = request.getParameter("extension");
//				obj.setExtension(extension);

String description = request.getParameter("description");
				obj.setDescription(description);

String remark = request.getParameter("remark");
				obj.setRemark(remark);

String document_type = request.getParameter("document_type");
                if (document_type != null && !document_type.isEmpty()) {
				    obj.setDocumentType(Integer.parseInt(document_type));
                }
				if (CommonBll.checkInputs(obj)) {

					int res = Integer.MIN_VALUE;
					try {
						res = dal.update(obj);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (res == 0) {
						// TODO success
						response.sendRedirect("documentList.jsp?objectType="+object_type+"&objectId="+object_id);
					} else {
						// TODO error
					}
				} else {
					request.setAttribute("document", obj);
					getServletContext().getRequestDispatcher("/documentList.jsp").forward(request, response);
				}
			} else {
				// TODO data not found
			}
		} else if (mode.equalsIgnoreCase("quickInsert")) {
			response.setContentType("text/xml; charset=UTF-8");
			DocumentModel obj = new DocumentModel();

			// SET NAME here

			GenericDal<DocumentModel, DocumentModelExt> dal = new GenericDal<DocumentModel, DocumentModelExt>(new DocumentModel());
			int res = 0;

			try {
				String strName = request.getParameter("document_name");
				strName = new String(strName.getBytes("ISO-8859-1"), "UTF-8"); // String(strName.getBytes("ISO-8859-1"),
																				// "UTF-8");
				obj.setDocumentName(strName);
				res = dal.insert(obj);

				PrintWriter out = response.getWriter();
				// TODO: check failed inserting case
				if (res > 0) {
					String resultXML = CommonUtil.createAjaxResultXML("document", "" + res);
					out.println(resultXML);
				}
				else
				{
					//TODO: respone something
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// TODO : return value

		}
	}

}